import os
import logging
from flask import Flask, render_template, request, jsonify
from dotenv import load_dotenv
from api_client import BusApiClient

# 加载环境变量
load_dotenv()

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger('bus_app')

app = Flask(__name__)

# 初始化API客户端
api_client = BusApiClient(
    username=os.getenv("API_USERNAME"),
    api_key=os.getenv("API_KEY")
)

@app.route("/")
def index():
    """网站首页"""
    logger.info(f"访问首页: {request.remote_addr}")
    return render_template("index.html")

@app.route("/api/cities", methods=["GET"])
def get_cities():
    """获取城市列表"""
    logger.info(f"API请求: 获取城市列表 - IP: {request.remote_addr}")
    try:
        result = api_client.get_cities()
        logger.info(f"API响应: 获取城市列表 - 成功")
        return jsonify(result)
    except Exception as e:
        logger.error(f"API响应: 获取城市列表 - 错误: {str(e)}")
        return jsonify({"error": str(e)}), 500

@app.route("/api/bus_lines", methods=["GET"])
def search_bus_lines():
    """搜索公交路线"""
    city_id = request.args.get("city_id")
    keywords = request.args.get("keywords")
    
    logger.info(f"API请求: 搜索公交路线 - IP: {request.remote_addr}, city_id: {city_id}, keywords: {keywords}")
    
    if not city_id or not keywords:
        logger.warning("API响应: 搜索公交路线 - 错误: 缺少必要参数")
        return jsonify({"error": "缺少必要参数"}), 400
        
    try:
        result = api_client.search_bus_lines(city_id, keywords)
        
        if result.get("return_code") == "ok":
            returl_list = result.get("returl_list", [])
            logger.info(f"API响应: 搜索公交路线 - 成功, 找到 {len(returl_list)} 条路线")
        else:
            logger.warning(f"API响应: 搜索公交路线 - API返回错误: {result.get('error_code')}")
            
        return jsonify(result)
    except Exception as e:
        logger.error(f"API响应: 搜索公交路线 - 错误: {str(e)}")
        return jsonify({"error": str(e)}), 500

@app.route("/api/bus_lines_complete", methods=["GET"])
def search_bus_lines_complete():
    """搜索公交路线（包含正向和反向）"""
    city_id = request.args.get("city_id")
    keywords = request.args.get("keywords")
    
    logger.info(f"API请求: 搜索公交路线(含反向) - IP: {request.remote_addr}, city_id: {city_id}, keywords: {keywords}")
    
    if not city_id or not keywords:
        logger.warning("API响应: 搜索公交路线(含反向) - 错误: 缺少必要参数")
        return jsonify({"error": "缺少必要参数"}), 400
        
    try:
        result = api_client.search_bus_lines_with_reverse(city_id, keywords)
        
        forward_data = result.get("forward_data", {})
        reverse_data = result.get("reverse_data", {})
        
        if forward_data.get("return_code") == "ok":
            forward_lines = forward_data.get("returl_list", [])
            reverse_lines = reverse_data.get("returl_list", []) if reverse_data.get("return_code") == "ok" else []
            
            logger.info(f"API响应: 搜索公交路线(含反向) - 成功, 找到正向 {len(forward_lines)} 条, 反向 {len(reverse_lines)} 条路线")
            
            # 合并结果
            response = {
                "return_code": "ok",
                "error_code": "0",
                "forward_data": forward_data,
                "reverse_data": reverse_data
            }
            
            return jsonify(response)
        else:
            logger.warning(f"API响应: 搜索公交路线(含反向) - API返回错误: {forward_data.get('error_code')}")
            return jsonify(forward_data)  # 返回正向查询的错误结果
            
    except Exception as e:
        logger.error(f"API响应: 搜索公交路线(含反向) - 错误: {str(e)}")
        return jsonify({"error": str(e)}), 500

@app.route("/api/bus_lines_reverse", methods=["GET"])
def search_bus_lines_reverse():
    """搜索公交反向路线"""
    city_id = request.args.get("city_id")
    keywords = request.args.get("keywords")
    
    logger.info(f"API请求: 搜索公交反向路线 - IP: {request.remote_addr}, city_id: {city_id}, keywords: {keywords}")
    
    if not city_id or not keywords:
        logger.warning("API响应: 搜索公交反向路线 - 错误: 缺少必要参数")
        return jsonify({"error": "缺少必要参数"}), 400
        
    try:
        result = api_client.search_bus_lines_reverse(city_id, keywords)
        
        if result.get("return_code") == "ok":
            returl_list = result.get("returl_list", [])
            logger.info(f"API响应: 搜索公交反向路线 - 成功, 找到 {len(returl_list)} 条路线")
        else:
            logger.warning(f"API响应: 搜索公交反向路线 - API返回错误: {result.get('error_code')}")
            
        return jsonify(result)
    except Exception as e:
        logger.error(f"API响应: 搜索公交反向路线 - 错误: {str(e)}")
        return jsonify({"error": str(e)}), 500

@app.route("/api/realtime_location", methods=["GET"])
def get_realtime_location():
    """获取公交实时位置"""
    city_id = request.args.get("city_id")
    bus_linestrid = request.args.get("bus_linestrid")
    bus_linenum = request.args.get("bus_linenum")
    bus_staname = request.args.get("bus_staname")
    
    logger.info(f"API请求: 获取公交实时位置 - IP: {request.remote_addr}, city_id: {city_id}, bus_staname: {bus_staname}")
    
    if not all([city_id, bus_linestrid, bus_linenum, bus_staname]):
        logger.warning("API响应: 获取公交实时位置 - 错误: 缺少必要参数")
        return jsonify({"error": "缺少必要参数"}), 400
        
    try:
        result = api_client.get_realtime_bus_location(
            city_id, bus_linestrid, bus_linenum, bus_staname
        )
        
        if result.get("return_code") == "ok":
            logger.info(f"API响应: 获取公交实时位置 - 成功")
        else:
            logger.warning(f"API响应: 获取公交实时位置 - API返回错误: {result.get('error_code')}")
            
        return jsonify(result)
    except Exception as e:
        logger.error(f"API响应: 获取公交实时位置 - 错误: {str(e)}")
        return jsonify({"error": str(e)}), 500

@app.route("/api/bus_schedule", methods=["GET"])
def get_bus_schedule():
    """获取发车时刻表"""
    city_id = request.args.get("city_id")
    bus_staname = request.args.get("bus_staname")
    
    logger.info(f"API请求: 获取发车时刻表 - IP: {request.remote_addr}, city_id: {city_id}, bus_staname: {bus_staname}")
    
    if not city_id or not bus_staname:
        logger.warning("API响应: 获取发车时刻表 - 错误: 缺少必要参数")
        return jsonify({"error": "缺少必要参数"}), 400
        
    try:
        result = api_client.get_bus_schedule(city_id, bus_staname)
        
        if result.get("return_code") == "ok":
            logger.info(f"API响应: 获取发车时刻表 - 成功")
        else:
            logger.warning(f"API响应: 获取发车时刻表 - API返回错误: {result.get('error_code')}")
            
        return jsonify(result)
    except Exception as e:
        logger.error(f"API响应: 获取发车时刻表 - 错误: {str(e)}")
        return jsonify({"error": str(e)}), 500

@app.route("/api/search_location", methods=["GET"])
def search_location():
    """换乘-地点搜索"""
    city_name = request.args.get("city_name")
    keywords = request.args.get("keywords")
    
    logger.info(f"API请求: 地点搜索 - IP: {request.remote_addr}, city_name: {city_name}, keywords: {keywords}")
    
    if not city_name or not keywords:
        logger.warning("API响应: 地点搜索 - 错误: 缺少必要参数")
        return jsonify({"error": "缺少必要参数"}), 400
        
    try:
        result = api_client.search_location(city_name, keywords)
        
        if result.get("return_code") == "ok":
            returl_list = result.get("returl_list", [])
            logger.info(f"API响应: 地点搜索 - 成功, 找到 {len(returl_list)} 个地点")
        else:
            logger.warning(f"API响应: 地点搜索 - API返回错误: {result.get('error_code')}")
            
        return jsonify(result)
    except Exception as e:
        logger.error(f"API响应: 地点搜索 - 错误: {str(e)}")
        return jsonify({"error": str(e)}), 500

@app.route("/api/plan_route", methods=["GET"])
def plan_route():
    """换乘-路线规划"""
    start_station = request.args.get("start_station")
    start_imlgn = request.args.get("start_imlgn")
    end_station = request.args.get("end_station")
    end_imlgn = request.args.get("end_imlgn")
    
    logger.info(f"API请求: 换乘路线规划 - IP: {request.remote_addr}, start: {start_station}, end: {end_station}")
    
    if not all([start_station, start_imlgn, end_station, end_imlgn]):
        logger.warning("API响应: 换乘路线规划 - 错误: 缺少必要参数")
        return jsonify({"error": "缺少必要参数"}), 400
        
    try:
        result = api_client.plan_route(start_station, start_imlgn, end_station, end_imlgn)
        
        if result.get("return_code") == "ok":
            returl_list = result.get("returl_list", [])
            logger.info(f"API响应: 换乘路线规划 - 成功, 找到 {len(returl_list)} 条路线")
        else:
            logger.warning(f"API响应: 换乘路线规划 - API返回错误: {result.get('error_code')}")
            
        return jsonify(result)
    except Exception as e:
        logger.error(f"API响应: 换乘路线规划 - 错误: {str(e)}")
        return jsonify({"error": str(e)}), 500

if __name__ == "__main__":
    logger.info("启动实时公交查询系统服务")
    app.run(debug=True) 